﻿using System;
using BoldBrick.Core.Logging;
using BoldBrick.OneIntranet.HR.Resources;
using BoldBrick.OneIntranet.HR.Utils;
using BoldBrick.SharePoint.CommonControls.Layouts;
using Microsoft.SharePoint;

namespace BoldBrick.OneIntranet.HR.Layouts
{
	public partial class ClosePositionPage : BaseDialogPage
	{
		private static readonly ILogger log = Logger.GetLogger(typeof(ClosePositionPage));

		#region ------ BaseDialogPage Members ----------------------------------------------------

		protected override string GetDescription(uint language)
		{
			this.DialogIconType = DialogIconTypes.Question;

			// get list
			SPList list = GetList(language);
			if (list == null)
				return null;

			// get item IDs

			if (this.QueryParameters.Items == null || this.QueryParameters.Items.Length == 0)
			{
				string message = ResourceBuilder.GetResource("ClosePositionPage_Error_NoItemID", language);
				ShowError(message, true);
				log.Write(LogLevel.Error, message);
				return null;
			}

			int itemID = this.QueryParameters.Items[0];
			SPListItem item = list.GetItemById(itemID);
			if (item == null)
			{
				string message = ResourceBuilder.GetResource("ClosePositionPage_Error_NoItem", language);
				ShowError(message, true);
				log.Write(LogLevel.Error, "Item with '{0}' ID not found in '{1}' list.", itemID, list.RootFolder.ServerRelativeUrl);
				return null;
			}

			// description
			string description = ResourceBuilder.GetResource("ClosePositionPage_Description", language);
			return description;
		}

		protected override string GetCancelButtonText(uint language)
		{
			return ResourceBuilder.GetResource("ClosePositionPage_CancelButton_Text", language);
		}

		protected override string GetOKButtonText(uint language)
		{
			return ResourceBuilder.GetResource("ClosePositionPage_OkButton_Text", language);
		}

		protected override string GetTitle(uint language)
		{
			return ResourceBuilder.GetResource("ClosePositionPage_Title", language);
		}

		
		#endregion

		#region ------ Action Methods ------------------------------------------------------------

		protected override bool DoAction(out string errorMessage)
		{
			errorMessage = null;
			uint language = SPContext.Current.Web.Language;

			SPListItem item = GetListItem(language);
			if (item == null)
				return false;

			try
			{
				PositionsHelper.ClosePosition(item);
			}
			catch (Exception ex)
			{
				log.Write(LogLevel.Error, ex, "'PositionsHelper.ClosePosition' method failed.");
				errorMessage = ex.Message;
				return false;
			}

			return true;
		}

		#endregion
	}
}
